$(function () {

    classesList()
    function classesList() {
        $.ajax({
            type: 'get',
            url: '/my/cate/list',
            success: function (res) {
                var htmlStr = template('tpl-table', res)
                $('tbody').html(htmlStr)
            }

        })
    }

    var layer = layui.layer
    var form = layui.form
    var indexAdd = null
    $('#btnadd').on('click', function () {
        indexAdd = layer.open({
            type: 1,
            area: ['500px', '250px'],
            title: '添加文章分类',
            content: $('#tpl-add').html(),
        });
    })


    $('body').on('submit', '#form-add', function (e) {
        e.preventDefault()
        console.log('ok');
        $.ajax({
            method: 'POST',
            url: '/my/cate/add',
            data: $(this).serialize(),
            success: function (res) {
                if (res.code !== 0) {
                    return layer.msg("新增文章分类失败！")
                }
                classesList()
                layer.msg("新增文章分类成功！")
                layer.close(indexAdd)
            }
        })
    })

    var indexEdit = null
    $('body').on('click', '.btn-edit', function (e) {
        // console.log('ok');
        indexEdit = layer.open({
            type: 1,
            area: ['500px', '250px'],
            title: '修改文章分类',
            content: $('#dialog-edit').html(),
        });

        var id = $(this).attr('data-id')
        // var id = $(this).siblings('#id').val()
        // console.log(id);

        $.ajax({
            type: 'GET',
            url: '/my/cate/info/?id=' + id,
            success: function (res) {
                console.log(res);
                form.val('form-edit', res.data)
            }
        })

    })


    $('body').on('submit', '#form-edit', function (e) {
        e.preventDefault()
        $.ajax({
            method: 'PUT',
            url: '/my/cate/info',
            data: $(this).serialize(),
            success: function (res) {
                if (res.code !== 0) {
                    return layer.msg("新增文章分类失败！")
                }

                layer.msg("新增文章分类成功！")
                layer.close(indexEdit)
                classesList()
            }
        })
    })

    $('body').on('click', '#btn-sc', function (e) {
        var id = $(this).attr('data-id')
        layer.confirm('确认删除?', { icon: 3, title: '提示' }, function (index) {
            $.ajax({
                method: 'DELETE',
                url: '/my/cate/del/?id=' + id,
                success: function (res) {
                    if (res.code !== 0) {
                        return layer.msg("删除文章分类失败！")
                    }
                    classesList()
                    layer.msg("删除文章分类成功！")
                    layer.close(indexEdit)
                }
            })

            layer.close(index);
        });

    })


})